package com.foyekoo.project001.activity;

import android.app.DialogFragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.foyekoo.project001.R;
import com.foyekoo.project001.command.Command;
import com.foyekoo.project001.command.ReceivedCommand;
import com.foyekoo.project001.config.LocalClient;
import com.foyekoo.project001.config.SpUtil;
import com.foyekoo.project001.service.BackgroundMusicService;
import com.foyekoo.project001.service.WaitingMusicService;
import com.foyekoo.project001.utils.BillUtil;
import com.foyekoo.project001.utils.ByteUtil;
import com.foyekoo.project001.utils.DialogUtil;
import com.foyekoo.project001.utils.LogUtil;
import com.foyekoo.project001.utils.MusicPlayFactory;
import com.foyekoo.project001.utils.PlayMusicTool;
import com.foyekoo.project001.utils.ReadThread;
import com.foyekoo.project001.utils.TimeUtil;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 待机页面
 */
public class WaitingActivity extends AppCompatActivity {


    @BindView(R.id.tv_coin_count)
    public TextView tv_coinCount;

    @BindView(R.id.tv_gameCount)
    public TextView tv_gameCount;

    @BindView(R.id.tv_game_by_one)
    public TextView tv_game_by_one;

    @BindView(R.id.tv_music_text)
    public TextView tv_musicText;

    @BindView(R.id.ll_playing_layout)
    public View playingView;

    @BindView(R.id.tv_time)
    public TextView tv_time;

    @BindView(R.id.iv_switch_image)
    public ImageView switchImage;

    int[] switchPicArray = {R.mipmap.bg_step1, R.mipmap.bg_step2, R.mipmap.bg_step3, R.mipmap.bg_step4};

    byte[] musicByteArray = {0x07, 0x08, 0x10, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x12};

    static int playMusicIndex = 0;

    private Handler handler = new Handler();



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setScreen();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        init();

        startService(new Intent(this, WaitingMusicService.class));


    }


    private void init() {
        LocalClient client = SpUtil.getInstance().getLocalClient();
        tv_coinCount.setText(client.alreadyCoin + "");
        tv_game_by_one.setText((client.coinByOneGame) + "币 / 1局");
        tv_time.setText(SpUtil.getInstance().getLocalClient().gameTime + "");
        playingView.setVisibility(View.GONE);
        Command.waitingUILoadingSuccess();
        if (SpUtil.getInstance().getLocalClient().freeMode == 1 ) { //如果是免费模式 那么修改一下币数
            tv_game_by_one.setText("免费模式");
        }


    }

    private void playMusic() {
        handler.removeCallbacks(musicRun);
        handler.postDelayed(musicRun, 0);//从本地拿到值 丢进去
    }

    private static MediaPlayer mediaPlayer;

    /**
     * 待机循环播音乐
     */
    private Runnable musicRun = new Runnable() {
        @Override
        public void run() {

            if (playMusicIndex >= musicByteArray.length - 1) {
                playMusicIndex = 0;
            }



            String text = MusicPlayFactory.getInstance().playMusic(musicByteArray[playMusicIndex], WaitingActivity.this);
            tv_musicText.setText(text);
            playMusicIndex++;
            handler.postDelayed(musicRun, SpUtil.getInstance().getLocalClient().waitingMusicInterval * 1000);//从本地拿到值 丢进去


        }
    };


    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(dataReceiver, new IntentFilter(ReadThread.ACTION_DATA_RECIEVE));
        sendBroadcast(new Intent(WaitingMusicService.ACTION_START));
        playMusic();
    }

    private static void closeMedia(){

    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(dataReceiver);
        sendBroadcast(new Intent(WaitingMusicService.ACTION_STOP));
        handler.removeCallbacks(musicRun);
    }

    public void setNavigationBarVisibility(boolean visible) {
        int flag = 0;
        if (!visible) {
            flag = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
        }

        getWindow().getDecorView().setSystemUiVisibility(flag);
    }

    //设置屏幕显示
    public void setScreen() {
        //去掉标题栏
        this.supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        //全屏显示
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        //去掉虚拟按键
        setNavigationBarVisibility(false);
    }

    android.support.v4.app.DialogFragment dialogFragment;

    public BroadcastReceiver dataReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            byte[] data = intent.getByteArrayExtra(ReadThread.EXTRA_DATA);

            if (data[2] == 0x02) {//电机初始化

                if (data[3] == 0x00 && data[4] == 0x01) {

                    dialogFragment = DialogUtil.showLoadingDialog(getSupportFragmentManager(), "电机校验中..");
                } else if (data[3] == 0x00 && data[3] == 0x02) {
                    dialogFragment.dismiss();
                    ;
                    dialogFragment = DialogUtil.showButtonDialog(getSupportFragmentManager(), "提示", "复位失败", null, null);

                } else if (data[3] == 0x00 && data[3] == 0x00) {
                    dialogFragment.dismiss();
                }

            }

            if (data[2] == 0x02){  //指令位  对应文档   这里是页面跳转
                if (data[3] == 0x03) {
                    Intent i = new Intent(context, BackgroundActivity.class);
                    i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    context.startActivity(i);
                }
            }

            if (data[2] == 0x10) { //切换图片
                switchImage.setImageResource(switchPicArray[data[3]]);
            }


            if (data[2] == 0x03) { //获取初始化时候的 局数 和投币数
                if (data[3] == 0x00) {
                    tv_game_by_one.setText("请投币             " + ((int) data[4]) + "币 / 1局");
                } else if (data[3] == 0x09) { //已投币数
                    int coinCount = data[4];
                    tv_coinCount.setText(coinCount + "");
                }
            } else if (data[2] == 0x04) {//这个要记录在账单里 币数

                int gameCount = data[3];

                tv_gameCount.setText(gameCount + "");

                byte[] coinData = new byte[2];
                coinData[0] = data[4];
                coinData[1] = data[5];

                int coin = Integer.parseInt(ByteUtil.byte2String(coinData), 16);

                LogUtil.d("WaitingActivity", "GameCount-->" + gameCount + ",->" + coin) ;

                if (coin > 0) {
                    handler.removeCallbacks(musicRun);
                }

                if (gameCount > 0 || coin > 0 ) {
                    startGame();
                } else  {
                    stopGame();
                }

                tv_coinCount.setText(Integer.parseInt(ByteUtil.byte2String(coinData), 16) + "");

                BillUtil.insert(TimeUtil.getTimeFormat("yyyy-MM-dd"), coin + "", "0");
            } else if (data[2] == 0x0B) { //音乐播放
                handler.removeCallbacks(musicRun);
                PlayMusicTool.close();
               ReceivedCommand.getPlayMusic(data);
            } else if (data[2] == 0x0E){ // y游戏时间实时更新
                tv_time.setVisibility(View.VISIBLE);
                tv_time.setText(ReceivedCommand.getCurrentPlayTime(data));
            }
        }
    };


    public void startGame(){
        playingView.setVisibility(View.VISIBLE);

    }

    public void stopGame(){
        tv_time.setText(SpUtil.getInstance().getLocalClient().gameTime + "");
        playingView.setVisibility(View.GONE);
        playMusic();

    }
}
